import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { viteMockServe  } from 'vite-plugin-mock'
import { ViteEjsPlugin } from 'vite-plugin-ejs'
import { resolve } from "path";
//import WindiCSS from 'vite-plugin-windicss'

import { fileURLToPath } from 'url';
import { createHtmlPlugin } from 'vite-plugin-html';

const root = process.cwd()
function pathResolve(dir) {
  return resolve(root, '.', dir)
}

// title1
const getTarget = (mode, target) => {
  return loadEnv(mode, process.cwd())[target];
 };
// https://vitejs.dev/config/
export default defineConfig(({command,mode })=>{
 const env=loadEnv(mode ,process.cwd()) // title2
 
 
//  console.log(env.VITE_APP_TITLE)//获取环境变量 
//  console.log(env.VITE_APP_API_BASEURL)//获取环境变量 
 return{  
   //envPrefix:  ['VUE','VITE'],   // 环境变量前缀,默认只会暴露VITE开头变量，定义后可暴露VUE开头变量
   define: {
    'process.env': {
      'VUE_APP_TITLE' : env.VITE_APP_TITLE,//getViteEnv(mode, "VITE_APP_TITLE"),// 动态.env中的指定环境变量
      'VUE_APP_API_BASEURL' : env.VITE_APP_API_BASEURL,
      'VUE_APP_PORT' : env.VITE_APP_PORT,
      'VUE_APP_PROXY' :env.VITE_APP_PROXY,
    }  
  }, 
  plugins: [
    vue(),
    ViteEjsPlugin({
      title: env.VITE_APP_TITLE
    }),
    viteMockServe({
      ignore: /^\_/,
      mockPath: 'mock',//解析根目录下的mock文件夹
      localEnabled: env.VITE_USE_MOCK_ENV ,  // 开发打包开关, //在开发环境中启用 mock
      prodEnabled: env.VITE_USE_MOCK_PRO ,  // 生产打包开关  //在生产环境中启用 mock
      supportTs:false,
      injectCode: `
          import { setupProdMockServer } from './mock/_createProMockServer'

          setupProdMockServer()
          `
    }),
    createHtmlPlugin({
      minify: true,
      entry: '/src/main.js',
      inject: {
        // Inject data into ejs template
        data: {
          VUE_APP_TITLE: env.VITE_APP_TITLE,
        },
        // Embed the generated app.config.js file   
      },
    }),
    //WindiCSS(),    
   ],     
  resolve: {
     extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.sass', '.css'],
    // 配置路径别名
     alias: [{
      find: 'vue-i18n',
      replacement: 'vue-i18n/dist/vue-i18n.cjs.js'
    },
    {
      find: /\@\//,
      replacement: `${pathResolve('src')}/`
    }]
     // {
    //     '@': resolve(__dirname, 'src'), // 设置 `@` 指向 `src` 目录     
    //     'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js'
    //   }, 
      
    },
    base: './',// 设置打包路径
    server:
    { 
      //allowedHosts: 'all',		
      open:true,//自动打开浏览器
      port:env.VITE_APP_PORT, //挂载端口
      //设置代理，根据我们项目实际情况配置
      proxy: {
        '/api': {
          target: env.VITE_APP_API_BASEURL,
          ws: true,
          changeOrigin: true,
          secure: false,    
          rewrite: (path) => path.replace(/^\/api/, '/')
        }
      }
    },
    build: {
      //target: 'es2015',
      // sourcemap: true
    },
  }
})